<template>
  <div class="yoyo-container mx-auto min-h-screen pb-[env(safe-area-inset-bottom)]">
    <!-- 导航栏 -->
    <navBar :title="$t('orders.title')"></navBar>

    <!-- 订单列表 -->
    <div class="mx-4 mt-4 space-y-3 pb-4">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" v-if="orders.length > 0">
        <van-list
          v-model="loading"
          :finished="finished"
          :finished-text="$t('query.noMoreData')"
          :loading-text="$t('query.loading')"
          @load="onLoad">
          <!-- 数据列表 -->
          <div v-for="(order, index) in orders" :key="index" class="bg-white rounded-xl px-3 py-2 shadow-sm mb-3">
            <div
              v-for="(item, index) in order.items"
              :key="index"
              @click="viewOrderDetails(order)"
              class="flex items-center border-b border-gray-100 py-2"
              :class="index === order.items.length - 1 ? 'border-b-0' : ''">
              <img :src="item.picUrl" alt="" class="w-12 h-12 rounded-lg" />
              <div class="ml-3 flex-1">
                <div class="flex items-center justify-between">
                  <span>{{ item.spuType }} {{ isZh ? item.spuName : item.spuNameEn }}</span>
                  <span>{{ isZh ? "¥" : "RM" }} {{ formatToYuan(item.price) }}</span>
                </div>
                <div class="flex items-center justify-between">
                  <span class="mr-1">
                    {{
                      isZh
                        ? item.dayValue.name + "&nbsp;" + item.packageValue.name
                        : item.dayValue.nameEn + "&nbsp;" + item.packageValue.nameEn
                    }}
                  </span>
                  <span>x{{ item.count }}</span>
                </div>
              </div>
            </div>

            <!-- <div class="flex justify-end space-x-3 mt-3">
              <van-button type="default" size="small" round class="border-gray-300" @click="viewOrderDetails(order)">查看详情</van-button>

              <van-button
                v-if="order.status === 'pending'"
                type="danger"
                size="small"
                round
                class="bg-red-500 border-none"
                @click="cancelOrder(order)">
                {{ $t("orders.cancelOrder") }}
              </van-button>
            </div> -->
          </div>
        </van-list>
      </van-pull-refresh>

      <!-- 空状态 -->
      <van-empty v-if="orders.length === 0" :description="$t('common.noData')" />
    </div>

    <!-- 取消订单确认弹窗 -->
    <van-dialog
      v-model="showCancelDialog"
      :title="$t('orders.confirmCancel')"
      show-cancel-button
      :confirm-button-text="$t('common.confirm')"
      :cancel-button-text="$t('common.cancel')"
      @confirm="confirmCancel" />
  </div>
</template>

<script>
import { Dialog, PullRefresh, List, Button, Empty } from "vant"
import { getOrderList } from "@/apis/order"
import { mapGetters } from "vuex"
import { formatToYuan } from "@/utils/common"

export default {
  name: "MyOrders",
  components: {
    [Dialog.Component.name]: Dialog.Component,
    [PullRefresh.name]: PullRefresh,
    [List.name]: List,
    [Button.name]: Button,
    [Empty.name]: Empty,
  },
  data() {
    return {
      showCancelDialog: false,
      currentOrder: null,
      // 模拟订单数据
      orders: [],
      loading: false,
      finished: false,
      refreshing: false,
      pageNo: 1,
      pageSize: 10,
      formatToYuan,
    }
  },
  computed: {
    ...mapGetters({
      isZh: "lang/isZh",
    }),
  },
  methods: {
    getStatusText(status) {
      const statusMap = {
        pending: this.$t("orders.statusPending"),
        shipped: this.$t("orders.statusShipped"),
        delivered: this.$t("orders.statusDelivered"),
        cancelled: this.$t("orders.statusCancelled"),
      }
      return statusMap[status] || status
    },

    getStatusClass(status) {
      const classMap = {
        pending: "text-[#ff7a00]",
        shipped: "text-blue-500",
        delivered: "text-green-500",
        cancelled: "text-red-500",
      }
      return classMap[status] || "text-gray-500"
    },

    viewOrderDetails(order) {
      // 跳转到订单详情页面
      this.$router.push({
        name: "orderDetail",
        query: {
          orderId: order.id,
        },
      })
    },

    cancelOrder(order) {
      this.currentOrder = order
      this.showCancelDialog = true
    },

    confirmCancel() {
      if (this.currentOrder) {
        // 模拟取消订单
        this.currentOrder.status = "cancelled"
        this.$toast.success(this.$t("orders.cancelSuccess"))
        this.currentOrder = null
      }
    },
    // 下拉刷新
    onRefresh() {
      this.pageNo = 1
      this.finished = false
      this.orders = []
      this.getOrderList()
    },

    // 上拉加载
    onLoad() {
      // this.pageNo += 1
      this.getOrderList()
    },
    async getOrderList() {
      try {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
        }
        const res = await getOrderList(params)
        const list = res.data.list
        console.log("订单列表:", res)
        if (this.refreshing) {
          this.orders = list
          this.refreshing = false
        } else {
          this.orders = [...this.orders, ...list]
        }

        this.loading = false

        // 判断是否已加载完所有数据
        if (res.data.total <= this.orders.length) {
          this.finished = true
        } else {
          this.pageNo++
        }
      } catch (error) {
        console.error("获取订单列表失败:", error)
      }
    },
  },
  created() {
    this.getOrderList()
  },
}
</script>

<style scoped>
/deep/ .van-sticky {
  width: 100%;
}

@media (width >= 40rem) {
  :deep(.van-sticky) {
    max-width: 40rem;
    margin-inline: auto;
    padding: 0 1rem;
  }
}

@media (width >= 48rem) {
  :deep(.van-sticky) {
    max-width: 48rem;
    margin-inline: auto;
    padding: 0 1rem;
  }
}

@media (width >= 64rem) {
  :deep(.van-sticky) {
    max-width: 64rem;
    margin-inline: auto;
    padding: 0 1rem;
  }
}

@media (width >= 80rem) {
  :deep(.van-sticky) {
    max-width: 80rem;
    margin-inline: auto;
    padding: 0 1rem;
  }
}

@media (width >= 96rem) {
  :deep(.van-sticky) {
    max-width: 96rem;
    margin-inline: auto;
    padding: 0 1rem;
  }
}
</style>
